'use strict';

// With background scripts you can communicate with popup
// and contentScript files.
// For more information on background script,
// See https://developer.chrome.com/extensions/background_pages

chrome.tabs.onActivated.addListener(async ({ tabId }) => {
  chrome.tabs.get(tabId, function(tab) {
    backgroundMessage('activeTab', tab)
    backgroundMessage('getSourceDomValue', {})
  })
});

function backgroundMessage(type, payload, callback) {
  chrome.tabs.query({ }, tabs => {
    tabs.forEach(tab => {
      chrome.tabs.sendMessage(
        tab.id,
        {
          type: type,
          payload: payload,
        },
        response => {
          callback && callback(response)
        }
      )
    })
  });
}

let contexts = [
  'page',
  'selection',
  'link',
  'editable',
  'image',
  'video',
  'audio'
];

chrome.runtime.onInstalled.addListener(function () {
  backgroundMessage('getSourceDomValue', {})
  chrome.contextMenus.create(
    { title: '粘贴内容', contexts: contexts, id: 'paste' }
  )
})

// A generic onclick callback function.
chrome.contextMenus.onClicked.addListener(genericOnClick);

// A generic onclick callback function.
function genericOnClick(info) {
  switch (info.menuItemId) {
    case 'paste':
      backgroundMessage('setTargetDomValue', {})
      break;
    default:
      break;
  }
}
